<template>
  <div>
    <h5 class="text-muted">当前任务：项目初审</h5>
    <el-form class="query-table-form" @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="企业名称查询"
          :clearable="true"
          @change="getData"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.lender_idcard"
          placeholder="身份证号码查询"
          :clearable="true"
          @change="getData"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.corp_name"
          placeholder="经营者名称查询"
          :clearable="true"
          @change="getData"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox
          v-model="params.has_ele_fee"
          border
          :true-label="1"
          :false-label="0"
          @change="getData"
        >
          电表
        </el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
    </el-form>

    <c-table border class="table-sm" v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:address="scope">
        <div class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</div>
      </template>

      <template v-slot:status="scope">
        <div
          class="badge"
          :class="`badge-${scope.row.statusStyle}`"
          :title="scope.row.pre_approval_des || ''"
        >
          {{ scope.row.statusLabel }}
        </div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <c-form-dialog
      label-width="200px"
      ref="form"
      title="项目初审"
      :form-items="formItems"
      :form-data="formData"
      :table-name="tableName"
      :table-id="tableId"
      :before-save="handleBeforeSave"
      :visible.sync="approvalVisible"
      :auto-close="false"
      :submit="false"
      :dismiss="false"
    >
      <template v-slot:res_divider>
        <p style="padding-left: 200px" class="text-muted">角色分配</p>
      </template>

      <el-form-item>
        <el-button
          @click="handleApprovalPass"
          class="btn-long"
          type="success"
          :loading="approvalLoading"
        >
          通过
        </el-button>
        <el-button
          @click="handleApprovalReject"
          class="btn-long"
          type="danger"
          :loading="approvalLoading"
        >
          不通过
        </el-button>
      </el-form-item>
    </c-form-dialog>

    <el-dialog
      :visible.sync="reportVisible"
      :close-on-click-modal="false"
      append-to-body
      top="30px"
      width="80%"
    >
      <el-tabs>
        <el-tab-pane label="数字档案">
          <credit-file :view-mode="true" :query-id="queryId"></credit-file>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>
<script>
import CreditFile from '@/credit/components/creditFile/Index'
import SelectOrgBank from '@/credit/components/select/SelectOrgBank'
import SelectStaff from '@/components/select/SelectStaff'
import { mapGetters } from 'vuex'
import { enumOrgClass, enumFarmType } from '@/credit/plugins/enum'
import { enumPreApproval } from '@/gov/plugins/enum'
const enumStatusStyle = {
  0: 'info',
  1: 'success',
  2: 'danger',
}

export default {
  components: {
    CreditFile,
  },
  props: {},
  data() {
    return {
      params: {
        index: 1,
        size: 10,
        lender_idcard: '',
        customer_name: '',
        corp_name: '',
        'submit_type.eq': 4,
      },
      loading: false,
      tableName: 'customer_related_view',
      tableData: [],
      totalCount: 0,
      tableColumns: [
        {
          attrs: { label: '主体名称', prop: 'customer_name', minWidth: '120px' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '地址', prop: 'address' }, slot: 'address' },
        {
          attrs: { label: '组织形式', prop: 'org_class', align: 'center' },
          process: v => enumOrgClass[v] || '-',
        },
        {
          attrs: { label: '企业类型', prop: 'farm_type', align: 'center' },
          process: v => enumFarmType[v] || '-',
        },
        { attrs: { label: '经营者姓名', prop: 'corp_name', align: 'center' } },
        { attrs: { label: '联系电话', prop: 'mobile_no', align: 'center' } },
        { attrs: { label: '申请金额（万元）', prop: 'apply_funds', align: 'center' } },
        { attrs: { label: '预审金额（万元）', prop: 'approved_funds', align: 'center' } },
        { attrs: { label: '客户来源', prop: 'submit_person_name', align: 'center' } },
        { attrs: { label: '推荐银行', prop: 'bank_name', align: 'center' } },
        { attrs: { label: '项目状态', prop: 'statusLabel', align: 'center' }, slot: 'status' },
        {
          attrs: { label: '操作', align: 'center' },
          operations: [
            // 市农担有预审 @石勇 2019-08-15
            {
              content: '初审',
              icon: 'fa fa-edit',
              event: this.handleEdit,
              ifRender: row => {
                return +row.is_approval === 0
              },
            },
            { content: '数字信用档案', icon: 'fa fa-file-text', event: this.handleView },
          ],
        },
      ],

      // 初审
      approvalVisible: false,
      tableId: '',
      formData: {},
      reason: [
        {
          tag: 'textarea',
          itemAttrs: {
            label: '不通过原因',
            rules: [{ required: true, message: '请填写不通过原因', trigger: 'blur' }],
          },
          attrs: { key: 'pre_approval_des', value: '' },
        },
      ],
      formItems: [
        {
          tag: SelectOrgBank,
          itemAttrs: {
            label: '贷款银行',
            rules: [{ required: true, message: '请选择贷款银行', trigger: 'blur' }],
          },
          attrs: { key: 'bank_code', class: 'form-control-ml', value: '', filterable: true },
          listeners: {
            select: bank => {
              this.bankName = bank.agency_name
            },
          },
        },
        {
          tag: 'input',
          itemAttrs: { label: '贷款银行' },
          attrs: { key: 'bank_name', class: 'form-control-ml', value: '' },
          ifShow: false,
          getValue: () => this.bankName,
        },
        {
          tag: 'number',
          itemAttrs: { label: '申请金额' },
          attrs: { key: 'apply_funds', value: '', disabled: true },
          tagSlots: [{ name: 'append', slot: '万元' }],
        },
        {
          tag: 'number',
          itemAttrs: {
            label: '建议金额',
            rules: [
              { required: true, message: '请填写建议金额', trigger: 'blur' },
              {
                validator: (rule, value, callback) => {
                  value = Number(value)
                  if (value <= 0) {
                    return callback(new Error('金额不能小于等于0'))
                  }
                  // if (value > 9999) {
                  //   return callback(new Error('贷款期限不能大于9999'))
                  // }
                  callback()
                },
                trigger: 'blur',
              },
            ],
          },
          attrs: { key: 'approved_funds', value: '' },
          tagSlots: [{ name: 'append', slot: '万元' }],
        },
        {
          tag: 'number',
          itemAttrs: {
            label: '贷款期限',
            step: 1,
            min: 0,
            max: 99,
            rules: [
              { required: true, message: '请填写贷款期限', trigger: 'blur' },
              {
                validator: (rule, value, callback) => {
                  value = Number(value)
                  if (!Number.isInteger(value)) {
                    return callback(new Error('请填写正确的贷款期限'))
                  }
                  if (value <= 0) {
                    return callback(new Error('贷款期限不能小于等于0'))
                  }
                  if (value > 99) {
                    return callback(new Error('贷款期限不能大于99'))
                  }
                  callback()
                },
                trigger: 'blur',
              },
            ],
          },
          attrs: { key: 'load_years', value: '' },
          tagSlots: [{ name: 'append', slot: '年' }],
        },
        {
          tag: 'input',
          attrs: { key: 'res_divider' },
          slot: 'res_divider',
          ifDrop: true,
        },
        {
          tag: SelectStaff,
          itemAttrs: {
            label: 'A角',
            rules: [{ required: true, message: '请选择A角', trigger: 'blur' }],
          },
          attrs: { key: 'res_a', value: '' },
        },
        {
          tag: SelectStaff,
          itemAttrs: {
            label: 'B角',
            rules: [{ required: true, message: '请选择B角', trigger: 'blur' }],
          },
          attrs: { key: 'res_b', value: '' },
        },
      ],
      bankName: '',
      approvalType: 1,
      approvalLoading: false,

      // 信用档案
      queryId: '',
      reportVisible: false,
    }
  },
  computed: {
    ...mapGetters(['user', 'userId', 'clientId', 'job']),
    isManager() {
      return ['org_credit_super', 'org_c_manage', 'org_r_emp', 'org_r_manage', 'org_corp'].includes(
        this.job
      )
    },
    // isUserTown() {
    //   return this.user.userRegionLever === 3
    // }
  },
  watch: {
    $route(route) {
      if (route.name === 'gxsPrelim') {
        this.getData()
      }
    },
  },
  created() {
    this.params['recommend_service.eq'] = this.clientId
    // if (this.isUserTown) {
    //   this.params['service_id.eq'] = this.clientId
    // } else {
    //   this.params['recommend_service.eq'] = this.clientId
    // }
    this.getData()
  },
  mounted() {},
  methods: {
    async getData() {
      const params = { ...this.params }
      const status = this.$route.query.status
      if (status !== undefined) {
        params['is_approval.eq'] = status
      }
      if (!this.isManager && status !== 0) {
        params['pre_approval_person.eq'] = this.userId
      }

      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, {
          create_time: 'desc',
        })
      )
      this.loading = false

      const data = (res && res.data) || {}
      this.totalCount = data.totalCount
      this.tableData = (data.data || []).map(item => {
        item.statusLabel = enumPreApproval[item.is_approval] || '-'
        item.statusStyle = enumStatusStyle[item.is_approval] || ''
        return item
      })
    },
    handleEdit(row) {
      this.formData = row
      this.approvalVisible = true
    },
    handleApprovalPass() {
      this.approvalType = 1
      this.$refs.form.submit()
    },
    async handleApprovalReject() {
      this.approvalType = 2
      const id = this.formData.customer_related_id
      this.$prompt('请输入未通过原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入不通过原因' : true),
      })
        .then(({ value }) => {
          this.approvalLoading = true
          this.$api
            .updateData(this.$serviceName, 'customer_related', id, {
              is_approval: this.approvalType,
              approval_person: this.userId,
              pre_approval_des: value,
              pre_approval_person: this.userId,
              pre_approval_date: this.$utils.dateFormat(new Date()),
              task_status: 1,
            })
            .then(() => {
              this.approvalLoading = false
              this.approvalVisible = false
              this.$message.success('审核成功')
              this.getData()
              this.$store.dispatch('getTaskCountGxs')
            })
            .catch(() => this.$message.error(`操作失败，请重试！`))
        })
        .catch(() => {})
    },
    async handleBeforeSave(model) {
      if (model.res_a === model.res_b) {
        this.$message.error('不能选择同一个人，请重新选择')
        return false
      }
      const id = this.formData.customer_related_id
      this.approvalLoading = true
      const [res] = await this.$utils.promise(
        this.$api.updateData(this.$serviceName, 'customer_related', id, {
          ...model,
          is_approval: this.approvalType,
          approval_person: this.userId,
          pre_approval_person: this.userId,
          pre_approval_date: this.$utils.dateFormat(new Date()),
          task_status: 1,
        })
      )
      this.approvalLoading = false

      if (res) {
        this.$message.success('审核成功')
        this.getData()
        this.$store.dispatch('getTaskCountGxs')
        this.approvalVisible = false
      } else {
        this.$message.error('审核失败，请重试')
      }

      return false
    },
    handleView(row) {
      this.queryId = row.customer_related_id
      this.reportVisible = true
    },
  },
}
</script>
<style lang="scss" scoped></style>
